<template>
  <div>
    <el-dialog
      title="切片分析结果"
      :visible.sync="dialogVisible"
      fullscreen>
      <div class="container">
        <div class="left-column">
          <div style="margin-left: calc(68vh);white-space: nowrap;height: 5%;margin-bottom: 10px">
            <i class="el-icon-circle-plus-outline" style="font-size: 30px" @click="zoomIn"></i>
            <span style="font-size: 26px;margin-left: 10px">{{ Math.round(scale*100) }}%</span>
            <i class="el-icon-remove-outline" style="font-size: 30px;margin-left: 10px" @click="zoomOut"></i>
          </div>
          <div class="doc-preview">
            <vue-office-docx
              v-if="this.fileType == 'docx'"
              :src="docxBase64Url"
              :style="{ transformOrigin: 'top left',transform: `scale(${scale})`,width:'1000px' }"
              @rendered="renderedHandler"/>
            <vue-office-pdf
              v-if="this.fileType == 'pdf'"
              :src="pdfBase64Url"
              :style="{ transformOrigin: 'top left',transform: `scale(${scale})` }"
              @rendered="renderedHandler"/>
            <vue-office-excel
              v-if="this.fileType == 'xlsx'"
              :src="excelBase64Url"
              :style="{ transformOrigin: 'top left',transform: `scale(${scale})` }"
              @rendered="renderedHandler"/>
            <img
              v-if="this.fileType == 'png' || this.fileType == 'jpg' || this.fileType == 'jpeg'"
              :src="imgBase64Url"
              :style="{ transformOrigin: 'top left',transform: `scale(${scale})`,width:'100%' }"/>
          </div>
        </div>
        <div class="right-column">
          <div style="white-space: nowrap;height: 5%;margin-bottom: 10px">
            <el-tooltip class="item" effect="dark" :content="'文件与解析结果所在目录：'+filepath" placement="bottom-start">
              <span style="font-size: 22px;margin-left: 10px;width: 100px">文件与解析结果所在目录：{{ formatStr(filepath) }}</span>
            </el-tooltip>
            <el-button style="float: right" type="primary" @click="exportTxt()">导出选中({{selectLength}})</el-button>
          </div>
          <div class="table-content">
            <vxe-table
              border
              resizable
              height="99%"
              ref="xTable"
              :loading="loading"
              :data="tableData"
              :edit-config="{trigger: 'manual', mode: 'row'}"
              @checkbox-all="selectAllEvent"
              @checkbox-change="selectChangeEvent">
              <vxe-column type="checkbox" width="60"></vxe-column>
              <vxe-column type="seq" width="60"></vxe-column>
              <vxe-column field="page_content" title="markdown预览">
              </vxe-column>
              <vxe-column field="page_content" title="分析结果" :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-textarea v-model="row.page_content" :autosize="{ maxRows: 200 }"  resize="vertical"></vxe-textarea>
                </template>
              </vxe-column>
              <vxe-column title="操作" width="160">
                <template #default="{ row }">
                  <template v-if="$refs.xTable.isActiveByRow(row)">
                    <div style="position: absolute; top: 10px; left: 10px;">
                      <vxe-button @click="saveRowEvent(row)" >保存</vxe-button>
                      <vxe-button @click="cancelRowEvent(row)">取消</vxe-button>
                    </div>
                  </template>
                  <template v-else>
                    <div style="position: absolute; top: 10px; left: 10px;">
                      <vxe-button @click="editRowEvent(row)" style="position: absolute; top: 0; left: 0;">编辑</vxe-button>
                    </div>
                  </template>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          <div class="page-content">
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getFileDetails"
            />
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeModel">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { docBase64,docDetail } from "@/api/knowledgemanagement/document";
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'
import VueOfficePdf from '@vue-office/pdf'
import '@vue-office/docx/lib/index.css'
import '@vue-office/excel/lib/index.css'
import { saveAs } from 'file-saver'

export default {
  components: { VueOfficeDocx ,VueOfficeExcel ,VueOfficePdf},
  props: {
    selectedKnowledgeId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      fileType: '',
      allowFile: ['pdf', 'jpg', 'jpeg', 'png', 'docx', 'xlsx', 'doc', 'csv'],
      docxBase64Url: '',
      docxBase64: 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,',
      pdfBase64Url: '',
      pdfBase64: 'data:application/pdf;base64,',
      excelBase64Url: '',
      excelBase64: 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,',
      imgBase64Url: '',
      scale: 1.0,  // 初始缩放比例
      minScale: 0.5,  // 最小缩放
      maxScale: 2,     // 最大缩放
      filepath: '',
      fileId: '',
      selectLength:0,
      loading: false,
      tableData: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
    };
  },
  methods: {
    open(data){
      this.dialogVisible = true
      this.fileId = data.file_id
      this.getFileBase64(data)
      this.getFileDetails(data)
    },
    getFileBase64(data){
      this.fileType = data.file_name.substring(data.file_name.lastIndexOf(".")+1)
      if(this.allowFile.includes(this.fileType)){
        docBase64({
          "kb_id": this.selectedKnowledgeId,
          "file_id": this.fileId
        }).then(res => {
          if(this.fileType == 'docx'){
            this.docxBase64Url = this.docxBase64 + res.data.file_base64
          }else if (this.fileType == 'pdf'){
            this.pdfBase64Url = this.pdfBase64 + res.data.file_base64
          }else if(this.fileType == 'xlsx'){
            this.excelBase64Url = this.excelBase64 + res.data.file_base64
          }else if(this.fileType == 'png' || this.fileType == 'jpg' || this.fileType == 'jpeg'){
            this.imgBase64Url = 'data:image/' + this.fileType + ';base64,' + res.data.file_base64
          }
        })
      }
    },
    getFileDetails(data){
      docDetail({
        "kb_id": this.selectedKnowledgeId,
        "file_id": this.fileId,
        "page_id": this.queryParams.pageNum,
        "page_limit": this.queryParams.pageSize
      }).then(res => {
        this.tableData = res.data.chunks
        this.total = res.data.total_count
        this.filepath = res.data.file_path
      })
    },
    closeModel(){
      this.dialogVisible = false
      this.docxBase64Url = ''
      this.pdfBase64Url = ''
      this.excelBase64Url = ''
      this.fileType = ''
      this.scale = 1.0
      this.selectLength = 0
    },
    renderedHandler() {
      console.log("渲染完成")
    },
    zoomIn() {
      this.scale = Math.min(this.scale + 0.1, this.maxScale)
    },
    zoomOut() {
      this.scale = Math.max(this.scale - 0.1, this.minScale)
    },
    formatStr(str) {
      if (!str) return '';
      return str.length > 40 ? `${str.slice(0, 40)}...` : str;
    },
    editRowEvent (row) {
      const $table = this.$refs.xTable
      $table.setEditRow(row)
    },
    saveRowEvent () {
      const $table = this.$refs.xTable
      $table.clearEdit().then(() => {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.$message({
            message: '保存成功',
            type: 'success'
          });
        }, 300)
      })
    },
    cancelRowEvent (row) {
      const $table = this.$refs.xTable
      $table.clearEdit().then(() => {
        // 还原行数据
        $table.revertData(row)
      })
    },
    selectAllEvent ({ checked }) {
      const records = this.$refs.xTable.getCheckboxRecords()
      this.selectLength = records.length
    },
    selectChangeEvent ({ checked }) {
      const records = this.$refs.xTable.getCheckboxRecords()
      this.selectLength = records.length
    },
    exportTxt(){
      const records = this.$refs.xTable.getCheckboxRecords()
      const content = records[0].page_content
      const blob = new Blob([content], {type: 'text/plain;charset=utf-8'})
      saveAs(blob, 'output.txt')
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  position: absolute;
  bottom: 10px;
  left: 0;
  right: 10px;
  padding: 10px;
  background: white;
}

.container {
  display: flex;
  width: 100%;
  max-height: calc(94vh - 120px);
}
.left-column {
  width: 40%;
}

.doc-preview{
  height: 95%;
  padding-top: 5px;
  border: 1px solid #ddd;
  border-radius: 20px;
  overflow: hidden;
  white-space: nowrap;
}

.doc-preview-pdf{
  height: 95%;
  padding-top: 5px;
  border: 1px solid #ddd;
  border-radius: 20px;
  overflow-y: auto;
}

.right-column {
  width: 59%;
  margin-left: 1%;
}

.table-content{
  height: 85%;
  padding-top: 5px;
  //border: 1px solid #ddd;
  //border-radius: 20px;
  overflow: auto;
}

.page-content{
  height: 10%;
  padding-top: 5px;
}
</style>
